<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\services\agent;

use app\model\advert\Advert;
use app\model\agent\AgentBankCard;
use app\model\agent\AgentBehaviourStatistic;
use app\model\agent\AgentLevel;
use app\model\agent\AgentMoneyLog;
use app\model\agent\AgentParams;
use app\model\agent\AgentProductShareStatistic;
use app\model\agent\AgentRelation;
use app\model\finance\FinanceStatistic;
use app\model\log\UserRechargeLog;
use app\model\order\Orders;
use app\model\product\product\StoreProduct;
use app\model\product\sku\StoreProductAttrValue;
use app\model\user\User;
use app\model\user\UserMoney;
use app\model\user\UserRecharge;
use app\model\user\UserSpread;
use app\services\BaseServices;
use app\services\order\StoreOrderCreateServices;
use app\services\order\StoreOrderServices;
use app\services\order\StoreOrderStatusServices;
use app\services\other\QrcodeServices;
use app\services\product\product\StoreProductServices;
use app\services\system\attachment\SystemAttachmentServices;
use app\services\user\UserAddressServices;
use app\services\user\UserBrokerageFrozenServices;
use app\services\user\UserBrokerageServices;
use app\services\user\UserExtractServices;
use app\services\user\UserServices;
use Carbon\Carbon;
use crmeb\exceptions\AdminException;
use crmeb\exceptions\ApiException;
use crmeb\services\app\MiniProgramService;
use app\services\other\UploadService;
use think\facade\Db;

/**
 *
 * Class AgentManageServices
 * @package app\services\agent
 */
class AgentManageServices extends BaseServices
{

    /**
     * @param array $where
     * @param bool $is_page
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function agentSystemPage(array $where, $is_page = true)
    {

        $query = User::with(['agentLevel', 'spreadUser'])->where('spread_time', '>', 0)->where('is_del', 0);

        $time = $where['time'] ?? [];
        if (isset($time[0]) && $time[0] > 0 && isset($time[1]) && $time[1] > 0) {
            $query->where('spread_time', '>=', $time[0])->where('spread_time', '<', $time[1]);
        }
        $nickname = $where['nickname'] ?? '';
        if ($nickname) {
            $query->where('nickname', 'like', '%' . $where['nickname'] . '%');
        }
        $spread_nickname = $where['spread'] ?? '';
        if ($spread_nickname) {
            $spread = User::where('nickname', 'like', '%'. $spread_nickname . '%')->where('is_del', 0)->find();
            if ($spread) {
                $query->where('spread_uid', $spread->uid);
            }
        }
        $agent_level = $where['agent_level'] ?? 0;
        if ($agent_level) {
            $query->where('agent_level', $agent_level);
        }

        $users = $query->paginate($where['limit'] ?? 15);

        $list = [];
        foreach ($users as $user) {
            $list[] = [
                'uid'    =>  $user->uid,
                'nickname'  =>  $user->nickname, // 昵称
                'phone' =>  $user->phone, // 手机号
                'mail' =>  $user->mail, // 邮箱
                'level_id' => $user->agentLevel ? $user->agentLevel->id : 0,
                'level_name' => $user->agentLevel ? $user->agentLevel->name : 0, // 等级
                'spread_nickname'  =>  $user->spreadUser ? $user->spreadUser->nickname : '', // 邀请方
                'deal_unit_price'   =>  $user->deal_unit_price, // 累计销售金额
                'brokerage_price'   =>  $user->brokerage_price, // 佣金金额
                'now_money' =>  $user->now_money, // 当前佣金(余额)
                'spread_time'   =>  $user->spread_time // 加入时间
            ];
        }

        return [
            'list'  =>  $list,
            'count' =>  $users->count()
        ];

//        /** @var UserServices $userServices */
//        $userServices = app()->make(UserServices::class);
//        $data = $userServices->getAgentUserList($where, '*', $is_page);
//        $frozenPrices = app()->make(UserBrokerageServices::class);
//        foreach ($data['list'] as &$item) {
//            $item['headimgurl'] = $item['avatar'];
//            $item['extract_count_price'] = $item['extract'][0]['extract_count_price'] ?? 0;
//            $item['extract_count_num'] = $item['extract'][0]['extract_count_num'] ?? 0;
//            $item['spread_name'] = $item['spreadUser']['nickname'] ?? '';
//            if ($item['spread_name']) {
//                $item['spread_name'] .= '/' . $item['spread_uid'];
//            }
//            $item['spread_count'] = $item['spreadCount'][0]['spread_count'] ?? 0;
//            $item['order_price'] = $item['order'][0]['order_price'] ?? 0;
//            $item['order_count'] = $item['order'][0]['order_count'] ?? 0;
//            $item['broken_commission'] = $frozenPrices->getUserFrozenPrice($item['uid']);
//            if ($item['broken_commission'] < 0)
//                $item['broken_commission'] = 0;
//            $item['new_money'] = $item['bill'][0]['brokerage_money'] ?? 0;
//            if ($item['brokerage_price'] > $item['broken_commission'])
//                $item['new_money'] = bcsub((string)$item['brokerage_price'], (string)$item['broken_commission'], 2);
//            else
//                $item['new_money'] = 0;
//            $item['brokerage_money'] = bcadd((string)$item['brokerage_price'], (string)$item['extract_count_price'], 2);
//            unset($item['extract'], $item['order'], $item['bill'], $item['spreadUser'], $item['spreadCount']);
//            if (strpos($item['headimgurl'], '/statics/system_images/') !== false) {
//                $item['headimgurl'] = set_file_url($item['headimgurl']);
//            }
//            $item['deal_count_money'] = $item['deal_number'] * $item['deal_unit_price'];
//        }
//        return $data;
    }

    /**
     * 分销头部信息
     * @param $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSpreadBadge($where)
    {
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        $uids = $userServices->getAgentUserIds($where);
        //分销员人数
        $data['uids'] = $uids;
        $data['sum_count'] = count($uids);
        $data['spread_sum'] = 0;
        $data['extract_price'] = 0;
        if ($data['sum_count']) {
            //发展会员人数
            $data['spread_sum'] = $userServices->getCount([['spread_uid', 'in', $uids]]);
            //获取某个用户可提现金额
            /** @var UserBrokerageFrozenServices $frozenPrices */
            $frozenPrices = app()->make(UserBrokerageFrozenServices::class);
            $data['extract_price'] = bcsub((string)$userServices->getSumBrokerage(['uid' => $uids]), $frozenPrices->getSumFrozenBrokerage($uids), 2);
        }
        //分销员人数
        $data['order_count'] = 0;
        $data['pay_price'] = 0;
        $data['pay_price'] = 0;
        $data['extract_count'] = 0;
        if ($data['sum_count']) {
            /** @var StoreOrderServices $storeOrder */
            $storeOrder = app()->make(StoreOrderServices::class);
            //订单总数
            $data['order_count'] = $storeOrder->getCount([['uid', 'in', $uids], ['paid', '=', 1], ['refund_status', '=', 0], ['pid', '<=', 0]]);
            //订单金额
            $data['pay_price'] = $storeOrder->sum([['uid', 'in', $uids], ['paid', '=', 1], ['refund_status', '=', 0], ['pid', '<=', 0]], 'pay_price');
            //提现次数
            $data['extract_count'] = app()->make(UserExtractServices::class)->getCount([['uid', 'in', $uids], ['status', '=', 1]]);
        }
        return [
            [
                'name' => '分销员人数(人)',
                'count' => $data['sum_count'],
                'className' => 'md-contacts',
                'col' => 6,
            ],
            [
                'name' => '推广用户数量(人)',
                'count' => $data['spread_sum'],
                'className' => 'md-contact',
                'col' => 6,
            ],
            [
                'name' => '订单数(单)',
                'count' => $data['order_count'],
                'className' => 'md-cart',
                'col' => 6,
            ],
            [
                'name' => '订单金额(元)',
                'count' => $data['pay_price'],
                'className' => 'md-bug',
                'col' => 6,
            ],
            [
                'name' => '提现次数(次)',
                'count' => $data['extract_count'],
                'className' => 'md-basket',
                'col' => 6,
            ],
            [
                'name' => '未提现金额(元)',
                'count' => $data['extract_price'],
                'className' => 'ios-at-outline',
                'col' => 6,
            ],
        ];
    }

    /**
     * 推广人列表
     * @param array $where
     * @return mixed
     */
    public function getStairList(array $where)
    {
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        $data = $userServices->getSairList($where);
        foreach ($data['list'] as &$item) {
            $item['spread_count'] = $item['spreadCount'][0]['spread_count'] ?? 0;
            $item['order_count'] = $item['order'][0]['order_count'] ?? 0;
            $item['promoter_name'] = $item['is_promoter'] ? '是' : '否';
            $item['add_time'] = $item['spread_time'] ? date("Y-m-d H:i:s", $item['spread_time']) : '';
        }
        return $data;
    }

    //TODO 废弃

    /**
     * 推广人头部信息
     * @param array $where
     * @return array[]
     */
    public function getSairBadge(array $where)
    {
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        $data['number'] = $userServices->getSairCount($where);
        $where['type'] = 1;
        $data['one_number'] = $userServices->getSairCount($where);
        $where['type'] = 2;
        $data['two_number'] = $userServices->getSairCount($where);

        $col = $data['two_number'] > 0 ? 4 : 6;
        return [
            [
                'name' => '总人数(人)',
                'count' => $data['number'],
                'col' => $col,
            ],
            [
                'name' => '一级人数(人)',
                'count' => $data['one_number'],
                'col' => $col,
            ],
            [
                'name' => '二级人数(人)',
                'count' => $data['two_number'],
                'col' => $col,
            ],
        ];
    }

    /**
     * 推广订单
     * @param int $uid
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getStairOrderList(int $uid, array $where)
    {
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        $userInfo = $userServices->getUserInfo($uid);
        if (!$userInfo) {
            return ['count' => 0, 'list' => []];
        }
        /** @var StoreOrderServices $storeOrder */
        $storeOrder = app()->make(StoreOrderServices::class);
        $data = $storeOrder->getUserStairOrderList($uid, $where);
        if ($data['list']) {
            $uids = array_unique(array_column($data['list'], 'uid'));
            $userList = [];
            if ($uids) {
                $userList = $userServices->getColumn([['uid', 'IN', $uids]], 'nickname,phone,avatar,real_name', 'uid');
            }
            $orderIds = array_column($data['list'], 'id');
            $orderChangTimes = [];
            if ($orderIds) {
                /** @var StoreOrderStatusServices $storeOrderStatus */
                $storeOrderStatus = app()->make(StoreOrderStatusServices::class);
                $orderChangTimes = $storeOrderStatus->getColumn([['oid', 'IN', $orderIds], ['change_type', '=', 'user_take_delivery']], 'change_time', 'oid');
            }
            foreach ($data['list'] as &$item) {
                $user = $userList[$item['uid']] ?? [];
                $item['user_info'] = '';
                $item['avatar'] = '';
                if (count($user)) {
                    $item['user_info'] = $user['nickname'] . '|' . ($user['phone'] ? $user['phone'] . '|' : '') . $user['real_name'];
                    $item['avatar'] = $user['avatar'];
                }
                $item['brokerage_price'] = $item['spread_uid'] == $uid ? $item['one_brokerage'] : $item['two_brokerage'];
                $item['_pay_time'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '';
                $item['_add_time'] = $item['add_time'] ? date('Y-m-d H:i:s', $item['add_time']) : '';
                $item['take_time'] = ($change_time = $orderChangTimes[$item['id']] ?? '') ? date('Y-m-d H:i:s', $change_time) : '暂无';
            }
        }
        return $data;
    }


    /**
     * 获取永久二维码
     * @param $type
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function wechatCode(int $uid)
    {
        /** @var QrcodeServices $qrcode */
        $qrcode = app()->make(QrcodeServices::class);
        $code = $qrcode->getForeverQrcode('spread', $uid);
        if (!$code['ticket']) throw new AdminException(410072);
        return $code;
    }

    /**
     * TODO 查看小程序推广二维码
     * @param string $uid
     */
    public function lookXcxCode(int $uid)
    {
        if (!sys_config('routine_appId') || !sys_config('routine_appsecret')) {
            throw new AdminException(400236);
        }
        $userInfo = app()->make(UserServices::class)->getUserInfo($uid);
        if (!$userInfo) {
            throw new AdminException(100026);
        }
        $name = $userInfo['uid'] . '_' . $userInfo['is_promoter'] . '_user.jpg';
        /** @var SystemAttachmentServices $systemAttachmentModel */
        $systemAttachmentModel = app()->make(SystemAttachmentServices::class);
        $imageInfo = $systemAttachmentModel->getInfo(['name' => $name]);
        if (!$imageInfo) {
            /** @var QrcodeServices $qrcode */
            $qrcode = app()->make(QrcodeServices::class);
            $resForever = $qrcode->qrCodeForever($uid, 'spread_routine');
            if ($resForever) {
                $resCode = MiniProgramService::appCodeUnlimitService($resForever->id, '', 280);
                $res = ['res' => $resCode, 'id' => $resForever->id];
            } else {
                $res = false;
            }
            if (!$res) throw new AdminException(400237);
            $upload = UploadService::init();
            if ($upload->to('routine/spread/code')->setAuthThumb(false)->stream((string)$res['res'], $name) === false) {
                return $upload->getError();
            }
            $imageInfo = $upload->getUploadInfo();
            $imageInfo['image_type'] = sys_config('upload_type', 1);
            $systemAttachmentModel->attachmentAdd($imageInfo['name'], $imageInfo['size'], $imageInfo['type'], $imageInfo['dir'], $imageInfo['thumb_path'], 1, $imageInfo['image_type'], $imageInfo['time'], 2);
            $qrcode->update($res['id'], ['status' => 1, 'time' => time(), 'qrcode_url' => $imageInfo['dir']]);
            $urlCode = $imageInfo['dir'];
        } else $urlCode = $imageInfo['att_dir'];
        return ['code_src' => $urlCode];
    }

    /**
     * 查看H5推广二维码
     * @param string $uid
     * @return mixed|string
     */
    public function lookH5Code(int $uid)
    {
        $userInfo = app()->make(UserServices::class)->getUserInfo($uid);
        if (!$userInfo) {
            throw new AdminException(100026);
        }
        $name = $userInfo['uid'] . '_h5_' . $userInfo['is_promoter'] . '_user.jpg';
        /** @var SystemAttachmentServices $systemAttachmentModel */
        $systemAttachmentModel = app()->make(SystemAttachmentServices::class);
        $imageInfo = $systemAttachmentModel->getInfo(['name' => $name]);
        if (!$imageInfo) {
            /** @var QrcodeServices $qrcodeService */
            $qrcodeService = app()->make(QrcodeServices::class);
            $urlCode = $qrcodeService->getWechatQrcodePathAgent($uid . '_h5_' . $userInfo['is_promoter'] . '_user.jpg', '?spread=' . $uid);
        } else $urlCode = $imageInfo['att_dir'];
        return ['code_src' => $urlCode];
    }

    /**
     * 清除推广关系
     * @param int $uid
     * @return mixed
     */
    public function delSpread(int $uid)
    {
        $userServices = app()->make(UserServices::class);
        $userInfo = $userServices->getUserInfo($uid);
        if (!$userInfo) {
            throw new AdminException(100026);
        }
        $spreadInfo = $userServices->get($userInfo['spread_uid']);
        $spreadInfo->spread_count = $spreadInfo->spread_count - 1;
        $spreadInfo->save();
        if ($userServices->update($uid, ['spread_uid' => 0, 'spread_time' => 0]) !== false) {
            return true;
        } else {
            throw new AdminException(400447);
        }
    }

    /**
     * 取消推广资格
     * @param int $uid
     * @return mixed
     */
    public function delSystemSpread(int $uid)
    {
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        if (!$userServices->getUserInfo($uid, 'uid')) {
            throw new AdminException(100026);
        }
        if ($userServices->update($uid, ['spread_open' => 0]) !== false)
            return true;
        else
            throw new AdminException(100020);
    }

    /**
     * 取消绑定上级
     * @return bool
     */
    public function removeSpread()
    {
        //商城分销功能是否开启 0关闭1开启
        if (!sys_config('brokerage_func_status')) return true;

        //绑定类型
        $store_brokergae_binding_status = sys_config('store_brokerage_binding_status', 1);
        if ($store_brokergae_binding_status == 1 || $store_brokergae_binding_status == 3) {
            return true;
        } else {
            //分销绑定类型为时间段且没过期
            $store_brokerage_binding_time = (int)sys_config('store_brokerage_binding_time', 30) * 24 * 3600;
            $spread_time = bcsub((string)time(), (string)$store_brokerage_binding_time, 0);
            /** @var UserServices $userServices */
            $userServices = app()->make(UserServices::class);
            $list = $userServices->getList(['not_spread_uid' => 0, 'status' => 1, 'spread_time' => ['<', $spread_time]], 'uid,spread_uid,spread_time');
            foreach ($list as $userInfo) {
                $userServices->update($userInfo['uid'], ['spread_uid' => 0, 'spread_time' => 0], 'uid');
            }
        }
        return true;
    }

    /**
     * 配置绑定类型切换重置绑定时间
     * @return bool
     */
    public function resetSpreadTime()
    {
        //商城分销功能是否开启 0关闭1开启
        if (!sys_config('brokerage_func_status')) return true;
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        $list = $userServices->getList(['not_spread_uid' => 0, 'status' => 1], 'uid');
        if ($list) {
            $uids = array_column($list, 'uid');
            $userServices->update([['uid', 'IN', $uids]], ['spread_time' => time()]);
        }
        return true;
    }


    public function recharge($amount, $phone, $remark, $admin_id)
    {
        if ($amount == 0) return true;

        $user = User::where('phone', $phone)->where('is_del', 0)->find();
        if (!$user) throw new AdminException(400214);
        $type = 1;
        $from_type = 2;
        $before_amount = $user->now_money;

        if (floatval($amount) < 0) {
            $type = 2;
        }

        $after_amount = $before_amount + floatval($amount);

        $this->transaction(function () use ($user, $type, $from_type, $amount, $before_amount, $after_amount, $remark, $admin_id) {

            $user->now_money = $after_amount;
            $user_res = $user->save();
            $recharge_log_res = UserRechargeLog::create([
                'uid'   =>  $user->uid,
                'before_amount' =>  $before_amount,
                'after_amount'  =>  $after_amount,
                'amount'    =>  $amount,
                'form_type' =>  $from_type,
                'type'  =>  $type,
                'remark'    =>  $remark,
                'operator_admin_id' =>  $admin_id,
                'add_time'  =>  time()
            ]);

            if ($user_res && $recharge_log_res) {
                return true;
            }
            return false;
        });

        return true;
    }

    public function actionList(array $time, $agent_nickname, $order_value, $order_type, $limit = 15)
    {
        $agent_behaviour_statistics = AgentBehaviourStatistic::with(['user'])->when(!empty($time), function ($query) use ($time) {
            $start_time = $time[0] ?? null;
            $end_time = $time[1] ?? null;
            if ($start_time && $end_time) {
                // 将时间戳转换为日期格式
                $start_date = date('Y-m-d', $start_time);
                $end_date = date('Y-m-d', $end_time);
                // 使用SUM()函数对字段进行求和
                $query->whereBetweenTime('statistic_date', $start_date, $end_date);
            }
        })
            ->when($agent_nickname, function ($query) use ($agent_nickname) {
                $query->hasWhere('user', function ($query) use ($agent_nickname) {
                    $query->where('nickname', 'like', '%'. $agent_nickname . '%');
                });
            })
            // 按uid分组，并对每个字段使用SUM()函数求和
            ->field('user_id, SUM(sale_count) as total_sale_count, SUM(register_nums) as total_register_nums, SUM(invitee_nums) as total_invitee_nums, SUM(product_share_nums) as total_product_share_nums, SUM(product_share_join_nums) as total_product_share_join_nums, SUM(product_share_view_nums) as total_product_share_view_nums')
            ->group('user_id')
            ->when($order_value, function ($query) use ($order_value, $order_type) {
                $orderField = '';
                switch ($order_value) {
                    case 1:
                        $orderField = 'total_sale_count';
                        break;
                    case 2:
                        $orderField = 'total_register_nums';
                        break;
                    case 3:
                        $orderField = 'total_invitee_nums';
                        break;
                    case 4:
                        $orderField = 'total_product_share_nums';
                        break;
                    case 5:
                        $orderField = 'total_product_share_join_nums';
                        break;
                    case 6:
                        $orderField = 'total_product_share_view_nums';
                        break;
                }
                if ($orderField) {
                    // 根据$order_value指定的字段进行排序
                    $query->orderRaw("$orderField " . ($order_type == 1 ? 'DESC' : 'ASC'));
                }
            })
            ->paginate($limit);


        $list = [];

        foreach ($agent_behaviour_statistics->items() as $item) {

            $phone = $item->user ? $item->user->phone : '';

            if (trim($phone) != '') {
                $phone = substr_replace($phone, '****', 3, 4);
            }

            $item['user'] = [
                'nickname'  =>  $item->user ? $item->user->nickname : '',
                'phone' =>  $phone
            ];

            $list[] = $item;
        }


        return [
            'list'  =>  $list,
            'count' =>  $agent_behaviour_statistics->count()
        ];
    }


    public function productList(array $time, $store_name, $order_value, $order_type, $limit = 15)
    {
        $agent_product_share_statistics = AgentProductShareStatistic::with(['product', 'attrInfo'])
            ->when(!empty($time), function ($query) use ($time) {
                $start_time = $time[0] ?? null;
                $end_time = $time[1] ?? null;
                if ($start_time && $end_time) {
                    // 将时间戳转换为日期格式
                    $start_date = date('Y-m-d', $start_time);
                    $end_date = date('Y-m-d', $end_time);
                    // 使用SUM()函数对字段进行求和
                    $query->whereBetweenTime('statistic_date', $start_date, $end_date);
                }
            })
            ->when(!empty($store_name), function ($query) use ($store_name) {
                $query->hasWhere('product', function ($subQuery) use ($store_name) {
                    $subQuery->where('store_name', 'like', '%' . $store_name . '%');
                });
            })
            // 按产品属性值分组，并对每个字段使用SUM()函数求和
            ->field('product_attr_value_unique, SUM(share_nums) as total_share_nums, SUM(view_people_nums) as total_view_people_nums, 
              SUM(deal_amount) as total_deal_amount, SUM(total_commission) as total_total_commission')
            ->group('product_attr_value_unique')
            ->when($order_value != 0, function ($query) use ($order_type, $order_value) {
                $orderField = '';
                switch ($order_value) {
                    case 1:
                        $orderField = 'total_share_nums';
                        break;
                    case 2:
                        $orderField = 'total_view_people_nums';
                        break;
                    case 3:
                        $orderField = '(SUM(share_nums) / SUM(view_people_nums))';
                        break;
                    case 4:
                        $orderField = 'total_deal_amount';
                        break;
                    case 5:
                        $orderField = 'total_total_commission';
                        break;
                }
                if ($orderField) {
                    // 根据$order_type指定的字段和$order_value进行排序
                    $query->orderRaw("$orderField " . ($order_type == 1 ? 'DESC' : 'ASC'));
                }
            })
            ->paginate($limit);
// 处理$agent_product_share_statistics中的数据...
// 计算view_pay_rate
        foreach ($agent_product_share_statistics as &$item) {
            if ($item['total_view_people_nums'] != 0) {
                $item['view_pay_rate'] = round($item['total_view_people_nums'] / $item['total_share_nums'], 2);
            } else {
                $item['view_pay_rate'] = 0.00; // 避免除以0的情况
            }

            // 获取商品
            $product = [
                'product_id'    =>  $item->attrInfo ? $item->attrInfo->product_id : 0,
                'image' =>  $item->attrInfo ? $item->attrInfo->image : '',
                'price' =>  $item->attrInfo ? $item->attrInfo->price : '',
                'suk'   =>  $item->attrInfo ? $item->attrInfo->suk : '',
                'unique'    =>  $item->product_attr_value_unique,
                'bar_code'  =>  $item->attrInfo ? $item->attrInfo->bar_code : '',
                'store_name'    =>  $item->product ? $item->product->store_name : ''
            ];

            $item['product'] = $product;
            unset($item['attrInfo']);

        }

        return [
            'list'  =>  $agent_product_share_statistics->items(),
            'count' =>  $agent_product_share_statistics->count()
        ];
    }

    public function agentSettlement(array $time, $agent_phone, $sn, $is_cal, $limit = 15)
    {

        $agentMoneyLogs = AgentMoneyLog::with(['buyer'])->when(!empty($time), function ($query) {
            $start_time = $time[0] ?? time()-86400*30;
            $end_time = $time[1] ?? time();
            $query->where('add_time', '>', $start_time)->where('add_time', '<', $end_time);
        })->when($agent_phone, function ($query) use ($agent_phone) {
            if ($agent_phone) {
                $query->hasWhere('agent', function ($query) use ($agent_phone) {
                    $query->where('phone', $agent_phone);
                });
            }
        })->when($sn, function ($query) use ($sn) {
            $query->hasWhere('order', function ($query) use ($sn) {
                $query->where('sn', $sn);
            });
        })->when($is_cal != -1, function ($query) use ($is_cal) {
            $query->where('cal_status', $is_cal);
        })->group('order_id')->paginate($limit);

        $list = [];

        foreach ($agentMoneyLogs as $log) {

            // 获取其中四级的数据
            $agent = [];
            $monet_logs = AgentMoneyLog::with('agent')->where('order_id', $log->order_id)->select();

            foreach ($monet_logs as $item) {
                $agent[] = [
                    'nickname'  =>  $item->agent ? $item->agent->nickname : '',
                    'phone' => $item->agent ? $item->agent->phone : '',
                    'money_type'    =>  $item->money_type,
                    'money' =>  $item->money,
                    'is_cal'    =>  $item->cal_status
                ];
            }

            $list[] = [
                'sn'    =>  $log->order ? $log->order->sn : '',
                'price' =>  $log->order ? $log->order->price : '',
                'buyer' =>  ($log->buyer) ? [
                    'id'    =>  $log->buyer_uid,
                    'nickname' =>   $log->buyer->nickname,
                    'phone' =>  $log->buyer->phone,
                ] : [
                    'id'    =>  $log->user_id,
                    'nickname' =>   '',
                    'phone' =>  '',
                ],
                'agent' =>  $agent,
            ];
        }

        return [
            'list'  =>  $list,
            'count' =>  $agentMoneyLogs->count()
        ];
    }

    public function makeCal(array $ids)
    {
        AgentMoneyLog::whereIn('id', $ids)->update(['cal_status' => 1]);
        return true;
    }


    public function getUserInfo($phone)
    {
        $user = User::where('phone', $phone)->where('is_del', 0)->find();

        return [
            'nickname' =>       $user ? $user->nickname : ''
        ];
    }


    public function agentSave($data){
        if(empty($data['phone']) || empty($data['nickname']) || empty($data['mail'])){
            throw new AdminException(60001);
        }
        $userServices = app()->make(UserServices::class);
        $userAddressServices = app()->make(UserAddressServices::class);



        $user = User::where('phone', $data['phone'])->where('is_del', 0)->find();
        if($user){//编辑分销员信息
            $info = ['phone' => $data['phone'],'nickname' => $data['nickname'],'spread_uid' => $data['spread_uid'],'agent_level' => $data['agent_level']];
            if (!$user->spread_time) {
                $info['spread_time'] = time();
            }
            $res1 = $userServices->updateField($user->uid, $info);

            $user->mail = $data['mail'];
            $res2 = $user->save();

//            $res2 = $userAddressServices->updateEmailByUid($user->uid,$data['mail']);
        }else{//添加分销员

            $res1 = $userServices->setUserInfo(['phone' => $data['phone'], 'nickname' => $data['nickname'], 'agent_level' => $data['agent_level']],$data['spread_uid']);
            $res1 = $res1->toArray();
            $res2 = $userAddressServices->addUserEmail(['mail' => $data['mail'],'uid' => $res1['uid'],'is_defalut' => 1,'is_del' => 0,'add_time' => time()]);
        }

        return $res1 && $res2;

    }

    public function getHomeIndex($user)
    {

        $total_reward_amount = AgentMoneyLog::where('user_id', $user->uid)->whereIn('money_type', [1,2,3,4])->group('order_id')->sum('money');
        $total_withdrawal = UserMoney::where('uid', $user->uid)->where('status', 1)->sum('number');


        $relation_uids = AgentRelation::where('first_puid', $user->uid)
            ->whereOr('second_puid', $user->uid)->whereOr('third_puid', $user->uid)->where('four_puid', $user->uid)->column('uid');


        $userMoneys = UserMoney::whereIn('uid', $relation_uids)->where('type', 3)->where('pm', 1)->where('status', 1)->sum('number');


        // 赚钱商品
        $commission_attr_values = StoreProductAttrValue::with(['product', 'stockRelation'])->hasWhere('product', function ($query) {
            $query->where('is_show', 1)->where('is_del', 0);
        })->where('join_agent', 1)->order('sales', 'desc')->order('commission', 'desc')->limit(6)->select();

        // 获取用户级别
        $agent = AgentLevel::where('grade', $user->agent_level)->where('status', 1)->where('is_del', 0)->find();

        $products = [];
        foreach ($commission_attr_values as $item) {
            $products[] = [
                'product_id'    =>  $item->product_id,
                'unique'    =>  $item->unique,
                'image' =>  $item->image,
                'price' =>  $item->price,
                'store_name' => $item->product ? $item->product->store_name : '',
                'fact_award'   => ($agent) ? number_format($item->commission * ($agent->one_brokerage / 100), 2) : '' ,
                'has_sale_stock'  =>  $item->stockRelation ? $item->stockRelation->has_sale_stock : 0,
            ];
        }
        return [
            'uid'   =>  $user->uid,
            'nickname' => $user->nickname,
            'level' => $user->level,
            'avatar'    =>  strpos($user->avatar, '/statics/system_images/') !== false ? set_file_url($user->avatar) : $user->avatar, // 用户头像
            'share_code'    =>  $user->share_code, // 用户分享码
            'now_money' =>  $user->now_money, // 用户余额
            'total_reward_amount'   =>  floatval($total_reward_amount), // 累计收益
            'total_withdrawal'  =>  $total_withdrawal, // 累计提现
            'team_users' => count($relation_uids), // 团队人数
            'team_commission'   =>  $userMoneys, // 团队佣金
            'products'  =>  $products,
            'invitee_code'  =>  ''
        ];
    }


    public function center($user)
    {
        $banner = Advert::where('pid', 1)->where('status', 1)->where(function ($query) {
            $query->where('time_type', 0)->whereOr(function ($query) {
                $time = Carbon::now();
                $query->where('time_type', 1)->where('start_time', '<=', $time)->where('end_time', '>', $time);
            });
        })->field('id,title,url,image_input')->select();

        $products = app()->make(StoreProductServices::class)->getHomeSeckillProductList($user);

        return compact('banner', 'products');
    }

    public function getLevelList($user)
    {
        // 获取用户已经推广的用户
        $invitee_nums = AgentRelation::where('first_puid', $user->id)->count();
        $has_recharge = UserRecharge::where('uid', $user->uid)->where('paid', 1)->sum('price');


        // 赚钱商品
        $commission_attr_values = StoreProductAttrValue::with(['product', 'stockRelation'])->hasWhere('product', function ($query) {
            $query->where('is_show', 1)->where('is_del', 0);
        })->where('join_agent', 1)->order('sales', 'desc')->order('commission', 'desc')->limit(3)->select();

        // 获取用户级别
        $agent = AgentLevel::where('grade', $user->agent_level)->where('status', 1)->where('is_del', 0)->find();

        $products = [];
        foreach ($commission_attr_values as $item) {
            $products[] = [
                'product_id'    =>  $item->product_id,
                'unique'    =>  $item->unique,
                'image' =>  $item->image,
                'price' =>  $item->price,
                'store_name' => $item->product ? $item->product->store_name : '',
                'fact_award'   => ($agent) ? number_format($item->commission * ($agent->one_brokerage / 100), 2) : '' ,
                'has_sale_stock'  =>  $item->stockRelation ? $item->stockRelation->has_sale_stock : 0,
            ];
        }


        return [
            'user'  =>  [
                'uid'   =>  $user->uid,
                'avatar'    =>  strpos($user->avatar, '/statics/system_images/') !== false ? set_file_url($user->avatar) : $user->avatar, // 用户头像
                'invitee_nums'  =>  $invitee_nums,
                'has_recharge'  =>  $has_recharge,
                'agent_level' =>  $user->agent_level
            ],
            'agent' =>  AgentLevel::where('status', 1)->where('is_del', 0)->order('grade', 'asc')->select(),
            'products'   =>  $products
        ];
    }


    public function upLevel($user, $up_to_level, $type)
    {

        if (!in_array($type, ['ALIPAY', 'GRABPAY'])) {
            throw new ApiException(410123);
        }

        $level = AgentLevel::where('id', $up_to_level)->where('is_del', 0)->where('use_recharge_amount', 1)->where('status', 1)->find();
        if (!$level) throw new ApiException(410071);


        if ($user->agent_level >= $up_to_level) throw new ApiException(31029);

        $this->transaction(function () use ($user, $level, $type) {

            $user->agent_level = $level->id;
            $user->save();

            $agentRelation = AgentRelation::where('uid', $user->uid)->find();
            if ($agentRelation) {
                $agentRelation->level = $level->id;
                $agentRelation->save();
            }

            // 记录log
            FinanceStatistic::create([
                'order_id'  =>  0,
                'sn'    => (app()->make(StoreOrderCreateServices::class))->getNewOrderId('cz'),
                'trade_type'    =>  4,
                'user_id'   =>  $user->uid,
                'trade_time'    =>  time(),
                'amount_type'   =>  1,
                'amount'    =>  $level->recharge_amount,
                'add_time'  =>  time()
            ]);

        });

        return true;
    }

    public function getProducts($user, $sort_type, $sort_value, $page)
    {

        $agent = AgentLevel::where('grade', $user->agent_level)->where('status', 1)->where('is_del', 0)->find();

//        // 获取热门分销
//        $hotProducts = [];
//        if ($page > 1) {
//            $storeProductAttrValues = StoreProductAttrValue::with(['product', 'stockRelation'])->hasWhere('product', function ($query) {
//                $query->where('is_show', 1)->where('is_del', 0);
//            })->where('join_agent', 1)->order('commission', 'desc')->limit(3)->select();
//
//            foreach ($storeProductAttrValues as $attrValue) {
//                $hotProducts[] = [
//                    'product_id'    =>  $attrValue->id,
//                    'image' =>  $attrValue->image,
//                    'commission'    =>  $attrValue->commission,
//                    'fact_award'   => ($agent) ? number_format($attrValue->commission * ($agent->one_brokerage / 100), 2) : '' ,
//                ];
//            }
//        }

        $order_value = ($sort_value) ? 'desc' : 'asc';

        $list = [];
        $storeProductAttrValues = StoreProductAttrValue::with(['stockRelation'])->hasWhere('product', function ($query) {
            $query->where('is_show', 1)->where('is_del', 0);
        })->where('join_agent', 1)
            ->when($sort_type == 2, function ($query) use ($order_value) {
            $query->order('id', $order_value);
        })->when($sort_type == 3, function ($query) use ($order_value) {
            $query->order('commission', $order_value);
        })->when($sort_type == 4, function ($query) use ($order_value) {
            $query->order('sales', $order_value);
        })->group('product_id')->limit(3)->select();

        foreach ($storeProductAttrValues as $attrValue) {
            $list[] = [
                'product_id'    =>  $attrValue->product_id,
                'image' =>  $attrValue->image,
                'commission'    =>  $attrValue->commission,
                'fact_award'   => ($agent) ? number_format($attrValue->commission * ($agent->one_brokerage / 100), 2) : '' ,
                'unique'    =>  $attrValue->unique,
                'price' =>  $attrValue->price,
                'store_name' => $attrValue->product ? $attrValue->product->store_name : '',
                'has_sale_stock'  =>  $attrValue->stockRelation ? $attrValue->stockRelation->has_sale_stock : 0,
            ];
        }

        return $list;

        // TODO 待完善
    }

    /**
     * 分销商品详情
     */
    public function productDetail($params)
    {
        $result = [];
        //产品
        $storeProductRow = StoreProduct::where('id', $params['product_id'])->find();
        //产品附加属性
        $storeProductAttrValueRows = StoreProductAttrValue::where('product_id', $params['product_id'])->select()->toArray();

        $result['product'] = [
            'store_name' => $storeProductRow->store_name,//商品名称
            'store_info' => $storeProductRow->store_info,//商品简介
            'price' => $storeProductRow->price,//价格
        ];
        //商品详情和商品参数
        $result['product_detail'] = [];
        $result['product_params'] = [];
        foreach($storeProductAttrValueRows as $key => $val) {
            if($key == 0) {
                //商品参数，暂无数据来源，写死
                $result['product_params'] = [
                    'address' => '中国 深圳',
                    'taste' => '草莓',
                    'net_content' => '10g'
                ];
            }
            $result['product_detail'][] = [

            ];
        }

        return $result;
    }

    /**
     * 分销规则
     */
    public function agentRule()
    {
        $agentParamsRow = AgentParams::where('is_enabled', 1)->find();

        return $agentParamsRow->rule ?? '';
    }

    /**
     * 佣金排行
     */
    public function commission($params)
    {
        /**
         * 根据sort_type字段判断
         * 1、平台排行 平台排行查询所有用户
         * 2、团队排行 团队排行查询团队内部排行
         */
        $listParams = [
            'where' => []
        ];
        if($params['sort_type'] == 2) {
            $userIds = self::getAgentUserIds($params['user_id']);
            $listParams['where'][] = ['user_id', 'IN', array_merge($userIds, [$params['user_id']])];
        }
        $listParams['fields'] = ['id', 'user_id', 'sale_count'];
        $listParams['order'] = [['field' => 'sale_count', 'type' => 'desc']];

        $result = $this->getModelList(AgentBehaviourStatistic::where('1=1'), $listParams);
        foreach($result['list'] as $key => $val) {
            $userRow = User::where('uid', $val['user_id'])->find();
            $result['list'][$key]['nickname'] = $userRow->nickname ?? '';
            $result['list'][$key]['avatar'] = $userRow->avatar ?? '';
        }

        return $result;
    }

    /**
     * 数据分析
     */
    public function analysis($params)
    {
        /**
         * 组合查询时间
         * 1、当天
         * 2、当周
         * 3、当月
         */
        $timeStampStart = strtotime("today", $params['time']);;
        $timeStampEnd = strtotime("tomorrow", $params['time']) - 1;
        if($params['date_type'] == 2) {
            $timeStampStart = strtotime("-1 week", $params['time']);
        }
        if($params['date_type'] == 3) {
            $timeStampStart = strtotime("-1 month", $params['time']);
        }
        //天数
        $dateNumber = date_interval_number($timeStampStart, $timeStampEnd);
        $dateArray = [];
        $newUserEcharts = [];
        $orderEcharts = [];
        for($i = $dateNumber; $i >= 0; $i--) {
            $dateArray[] = date('Y-m-d', strtotime('-' . $i . ' day', $timeStampEnd));
            $newUserEcharts[] = 0;
            $orderEcharts[] = 0;
        }
        //print_r([$timeStampStart, $timeStampEnd]);exit;
        $newUserQuery = UserSpread::where('spread_uid', $params['user_id'])->where([
            ['spread_time', '>=', $timeStampStart],
            ['spread_time', '<=', $timeStampEnd],
        ]);
        //拉新人数
        $newUserNumber = $newUserQuery->count();
        //拉新人ID合集
        $spreadUserIds = $newUserQuery->column('uid');
        $newUserRows = $newUserQuery->field("count(*) as total, date_format(FROM_UNIXTIME(spread_time),'%Y-%m-%d') as dates")->group('dates')->select()->toArray();
        //拉新人数echarts图表
        array_walk($newUserRows, function ($val, $key) use ($dateArray, &$newUserEcharts) {
            $index =array_search($val['dates'], $dateArray);
            $newUserEcharts[$index] = $val['total'];
        });

        $orderQuery = Orders::where('uid', 'IN', array_merge($spreadUserIds, [$params['user_id']]))->where([
            ['add_time', '>=', $timeStampStart],
            ['add_time', '<=', $timeStampEnd],
        ]);
        //订单数量
        $orderNumber = $orderQuery->count();
        $orderRows = $orderQuery->field("count(*) as total, date_format(FROM_UNIXTIME(add_time),'%Y-%m-%d') as dates")->group('dates')->select()->toArray();
        //订单数量echarts图表
        array_walk($orderRows, function ($val, $key) use ($dateArray, &$orderEcharts) {
            $index =array_search($val['dates'], $dateArray);
            $orderEcharts[$index] = $val['total'];
        });

        //个人佣金
        $oneAgent = 0.00;
        //团队佣金
        $teamAgent = 0.00;
        //个人佣金和团队佣金echarts图表
        $oneAgentEcharts = [];
        $teamAgentEcharts = [];

        $result = [
            'new_user_number' => $newUserNumber,
            'order_number' => $orderNumber,
            'one_agent' => $oneAgent,
            'team_agent' => $teamAgent,
            'echarts_date_array' => $dateArray,
            'new_user_echarts' => $newUserEcharts,
            'order_echarts' => $orderEcharts,
            'one_agent_echarts' => $oneAgentEcharts,
            'team_agent_echarts' => $teamAgentEcharts,
        ];

        return $result;
    }

    /**
     * 银行卡添加
     */
    public function bankCardAdd($params)
    {
        Db::transaction(function () use ($params) {
            $id = AgentBankCard::insertGetId($params);
            if(!$id) {
                throw new ApiException(100005);
            }
        });
    }

    /**
     * 编辑银行卡
     * @param $params
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function bankCardEdit($params)
    {

        $agent_bank_card = AgentBankCard::where('id', $params['id'])->find();
        if (!$agent_bank_card) {
            throw new ApiException(31020);
        }
        Db::transaction(function () use ($params, $agent_bank_card) {

            $res = $agent_bank_card->update($params);

            if(!$res) {
                throw new ApiException(100005);
            }
        });
    }

    public function bankCardDetail($id, $user_id = 0)
    {
        $bankCard = AgentBankCard::where('id', $id)->where('user_id', $user_id)->field('id,account_name,card_number,bank_name')->find();
        if (!$bankCard) return [];
        return $bankCard->toArray();
    }

    /**
     * 银行卡列表
     */
    public function bankCardList($params)
    {
        $listParams = [
            'where' => [['user_id', '=', $params['user_id']]],
            'order' => [['field' => 'id', 'type' => 'desc']],
        ];
        $result = $this->getModelList(AgentBankCard::where('1=1'), $listParams);

        return $result;
    }

    /**
     * 银行卡删除
     */
    public function bankCardDelete($params)
    {
        Db::transaction(function () use ($params) {
            AgentBankCard::destroy($params['agent_bank_card_id']);
        });
    }

    /**
     * 团队信息
     */
    public function teamInfo($params)
    {
        $result = ['sale_count' => 0.00, 'register_nums' => 0];
        $agentBehaviourStatisticsRow = AgentBehaviourStatistic::where('user_id', $params['user_id'])->order('statistic_date desc')->find();
        if(!empty($agentBehaviourStatisticsRow)) {
            $result['sale_count'] = $agentBehaviourStatisticsRow->sale_count;
            $result['register_nums'] = $agentBehaviourStatisticsRow->register_nums;
        }

        return $result;
    }

    /**
     * 团队列表
     */
    public function teamList($params)
    {

        $limit = $params['limit'] ?? 10;

        $account = $params['account'] ?? '';

        // 获取我的团队
        $query = AgentRelation::hasWhere('user', function ($query) use ($account) {
            $query->where('is_del', 0);
            if ($account) {
                $query->where('account', 'like', '%'. $account . '%')->whereOr('phone', 'like', '%' . $account . '%');
            }
        })->with(['user'])->where(function ($query) use ($params) {
            $query->where('first_puid', $params['user_id'])
                ->whereOr('second_puid', $params['user_id'])
                ->whereOr('third_puid', $params['user_id'])
                ->whereOr('four_puid', $params['user_id']);
        });

        $sort_value = (isset($params['sort_value']) && $params['sort_value'] == 1) ? 'asc' : 'desc';

        if (isset($params['order_type'])) {
           switch ($params['order_type']) {
               case 1: // 注册时间
                   $query->order('User.add_time '. $sort_value);
                   break;
               case 2: // 收益
                   $query->order('income '. $sort_value);
                   break;
               case 3: // 订单
                   $query->order('order_nums ' . $sort_value);
           }
        }

        $agentRelation = $query->paginate($limit);


        $result = [];
        foreach($agentRelation as $key => $val) {
            $user = $val->user;
            $result[$key]['uid'] = $user->uid;
            $result[$key]['nickname'] = $user->nickname;
            $result[$key]['avatar'] = $user->avatar;

            $result[$key]['add_time'] = date('Y-m-d', $user['add_time']);
            $result[$key]['sale_count'] = $val->total_amount;
            $result[$key]['indirect'] = ($val->first_puid != $params['user_id']) ? 1 : 0;
            //订单相关
            $result[$key]['order_number'] = $val->order_nums;
            $result[$key]['total_money'] = $val->income;
        }

        return [
            'count' => $agentRelation->count(),
            'list'  =>  $result
        ];



        //递归获取分销团队用户ID数组
//        $listParams = [];
//        $userIds = self::getAgentUserIds($params['user_id']);
//        if(count($userIds)) {
//            $listParams['where'][] = ['uid', 'IN', $userIds];
//        }
//        if(!empty($params['account'])) {
//            $listParams['where'][] = ['account', 'LIKE', '%' . $params['account'] . '%'];
//        }
//        if (!empty($params['start_time']) && !empty($params['end_time'])) {
//            $listParams['where'][] = ['add_time', '>=', Carbon::parse($params['start_time'])->timestamp];
//            $listParams['where'][] = ['add_time', '<=', Carbon::parse($params['end_time'])->timestamp];
//        }
//
//        $listParams['fields'] = ['uid', 'nickname', 'add_time'];
//
//        // 处理order
//        if (!empty($params['sort_type']) && !empty($params['sort_value'])) {
//            $listParams['order'] = [
//                'field' => $params['sort_value'],
//                'type' => $params['sort_type']
//            ];
//        }
//
//        dd($listParams);
//
//        $result = $this->getModelList(User::where('1=1'), $listParams);
//        foreach($result['list'] as $key => $val) {
//            $result['list'][$key]['add_time'] = date('Y-m-d H:i:s', $val['add_time']);
//            $result['list'][$key]['sale_count'] = AgentBehaviourStatistic::where('user_id', $val['uid'])->value('sale_count');//分销总金额
//            //订单相关
//            $orderQuery = AgentMoneyLog::where('user_id', $val['uid']);
//            $result['list'][$key]['order_number'] = $orderQuery->count();
//            $result['list'][$key]['total_money'] = $orderQuery->sum('money');
//        }
//
//        return $result;

    }

    /**
     * @param $userId
     * @return array
     * 递归获取所有分销用户ID合集
     */
    public static function getAgentUserIds($userId)
    {
        $result[] = $userId;
        $userIds = UserSpread::where('spread_uid', $userId)->column('uid');
        foreach($userIds as $key => $val) {
            $result = array_merge($result, self::getAgentUserIds($val));
        }

        return $result;
    }
}
